import Clock from './Clock';
import { Delayed, Type } from './Delayed';

export default class ClockTimer extends Clock {
  public delayed: Delayed[] = [];

  constructor(autoStart: boolean = false) {
    super(autoStart);
  }

  public tick() {
    super.tick();

    let i = this.delayed.length;
    while (i--) {
      const delayed = this.delayed[i];

      if (delayed.active) {
        delayed.tick(this.deltaTime);

      } else {
        this.delayed.splice(i, 1);
        continue;
      }
    }
  }

  public setInterval(handler: Function, time: number, ...args: any[]) {
    const delayed = new Delayed(handler, args, time, Type.Interval);
    this.delayed.push(delayed);
    return delayed;
  }

  public setTimeout(handler: Function, time: number, ...args: any[]) {
    const delayed = new Delayed(handler, args, time, Type.Timeout);
    this.delayed.push(delayed);
    return delayed;
  }

  public clear() {
    let i = this.delayed.length;
    while (i--) { this.delayed[i].clear(); }
    this.delayed = [];
  }
}
